<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/10/15
 * Time: 22:30
 */
namespace app\service;

use app\model\Wx;
use think\facade\Config;
use think\facade\Log;
use think\Service;
use tool\Curl;
use wx\WxCrypt;

class WxService extends Service
{
    private static $appId = 'wx304fe01cadbb18fd';
    private static $appSecret = '20e5950d30f66010a6a27b74dc736a64'; //小程序
    private static $officialSecret = '25b402db887d82ef8719c7089fb6d690'; //公众号

    public function __construct()
    {

    }

    /**
     * 获取 access_token
     * @return bool|string
     */
    public static function getAccessToken()
    {
        $wxModel = new Wx();
        $info = $wxModel->getAccessToken(self::$appId);
        if($info && $info['wt_expires_time']>0 && $info['wt_expires_time'] >= time()){
            return $info['wt_access_token'];
        }
        $api = sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",self::$appId,self::$appSecret);
        $rt = Curl::get($api);

        if($rt){
            $accessToken = isset($rt['access_token']) ? $rt['access_token'] : '';
            $expires = isset($rt['expires_in']) ? $rt['expires_in'] : 0;
            $expireTime = time() + $expires;

            $wxAccessToken = [
                'wt_access_token' => $accessToken,
                'wt_expires_in' => $expires,
                'wt_expires_time' => $expireTime,
            ];
            $wxModel->updateAccessToken(self::$appId,$wxAccessToken);

            return $accessToken;
        }

        return false;
    }


    /**
     * 小程序登录
     * @param $code
     * @return array|bool|mixed
     */
    public function code2Session($code)
    {
        $api = sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",self::$appId,self::$appSecret,$code);
        $rt = Curl::get($api);
        return $rt && isset($rt['openid']) ? $rt : false;
    }

    /**
     * 生成二维码  小程序
     * @param string $path
     * @param int $width
     * @return mixed
     */
    public function createQRCode($path = 'pages/index/index',$width = 430)
    {
        $accessToken = self::getAccessToken();
        $api = sprintf("https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=%s",$accessToken);

        $data = [
            'path' => $path,
            'width' => $width
        ];

        $rt = Curl::post($api,[],json_encode($data),false,false);

        if($rt){
            $qnService = new QiniuService();
            $file = $qnService->put($rt);
            return $file[0]['key'];
        }
        return false;
    }

    /**
     * 生成二维码 无限制
     * @param string $path
     * @param string $param
     * @param int $width
     * @return mixed
     */
    public function getwxacodeunlimit($path = '',$param = '',$width = 1000,$type = 1)
    {
        $accessToken = self::getAccessToken();
        $api = sprintf("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s",$accessToken);
        $api = sprintf("https://api.weixin.qq.com/wxa/getwxacode?access_token=%s",$accessToken);

        $data = [
            'path' => $path.$param,
            'width' => $width,
            'is_hyaline' => true,
//            'scene' => $param
        ];

        $rt = Curl::post($api,[],json_encode($data),false,false);

        if($rt){
            $err = json_encode($rt,true);
            if(isset($err['errcode']))    return false;

            $qnService = new QiniuService();
            $file = $qnService->put($rt);

            $imgService = new ImgService();
//            $rt = $imgService->getQrcode(fileFullPath($file[0]['key']));
            $rt = $imgService->getQrcode($rt,$type);

            $file = $qnService->put($rt);
            return $file[0]['key'];

        }
        return false;
    }

    /**
     * 解密小程序 加密信息
     * @param $sessionKey
     * @param $encryptedData
     * @param $iv
     * @return int|mixed
     */
    public function dataCrypt($sessionKey,$encryptedData,$iv){

        $crypt = new WxCrypt(self::$appId,$sessionKey);
        $errCode = $crypt->decryptData($encryptedData,$iv,$data);

        Log::write([$sessionKey,$encryptedData,$iv,$data]);
        if($errCode == 0){
            return json_decode($data,true);
        }

        return $errCode;
    }

}